package queue_stack.leetcode.medium;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author bruin_du
 * @description 二叉树每层的最大值
 * @date 2022/8/13 23:37
 **/
public class OfferII044_LargestValues {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int size = 1;
        while (!queue.isEmpty()) {
            int num = 0, max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                max = Math.max(max, node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                    num++;
                }
                if (node.right != null){
                    queue.offer(node.right);
                    num++;
                }
            }
            list.add(max);
            size = num;
        }
        return list;
    }
}
